import React, { Component, createRef, useState } from 'react'
import { Table, Space, Card, Modal, Button, message, Form, Input } from 'antd';
import '../../utils/axios'
import AddCAtegory from './addCAtegory';
import { addListPost, deleteListPost, updateCategories } from '../../api/categories'

//获取后台数据方法1：使用export暴露单个响应的函数，然后通过这里引入
// import { getAllList } from '../../api/categories.js'

//获取后台数据方法2：使用export default暴露整个函数对象，然后通过这里引入
// import getAll from '../../api/categories.js'

//获取后台数据方法3：使用状态机
import { connect } from 'react-redux';
import { getCategoriesAsyncAction } from '../../redux/actions/categoriesActions'


class Categories extends Component {
    state = {
        // data: [
        //     { "_id": "5fbcce80ea6c0000ff007f3a", "createDate": null, "name": "医药保健", "parentId": "0", "type": "一级分类", "updateDate": null }
        // ]
        isModalVisible: false,
        parentId: 0,
        isUpdateVisible: false,
        updateData:{}
    }
    // 进行挂载
    componentDidMount() {
        this.getAllList()
    }
    inputRef = createRef()
    //获取后台数据方法1：这里开始调用我们暴露的方法
    // getAllList=async ()=>{
    //     const res=await getAllList({parentId:0})
    //     console.log(res);
    //     if (res.code) {
    //         this.setState({
    //             data:res.data.data
    //         })
    //     }
    // }

    //获取后台数据方法2：这里开始调用我们暴露的方法
    // getAllList=async ()=>{
    //     const res=await await getAll.getAllList({parentId:0})
    //     console.log(res);
    //     if (res.code) {
    //         this.setState({
    //             data:res.data.data
    //         })
    //     }
    // }

    //获取后台数据方法3：这里使用dispatch调用异步action
    getAllList = async () => {
        // 指定action命令，让saga侦听，并做出相应操作
        this.props.dispatch(getCategoriesAsyncAction({ parentId: this.state.parentId }))
    }
    //是否显示模态框
    showModal = () => {
        this.setState({
            isModalVisible: true
        })
    };
    //模态框点击确定
    handleOk = async () => {
        const res = await addListPost(this.inputRef.current.state.addCategroy)
        console.log(res);
        if (res.code) {
            message.success(res.msg);
            this.getAllList()
            this.setState({
                isModalVisible: false
            })
        } else {
            message.warning(res.msg);
        }

    };
    //模态框点击退出
    handleCancel = () => {
        this.setState({
            isModalVisible: false
        })
    };
    // 点击删除
    async deleteCategory(id) {
        console.log(id);
        const res = await deleteListPost({ id })
        console.log(res);
        if (res.code) {
            message.success(res.msg);
            this.getAllList()
        } else {
            message.warning(res.msg);
        }
    }
    // 返回上一级
    back = () => {
        this.setState({
            parentId: 0
        },
            () => {
                this.getAllList()
            }
        )
    }




    // 修改
    showUpdateModal = (record) => {
        console.log(record);
        this.setState({
            isUpdateVisible: true,
            updateData:record
        })
    };

    handleUpdateOk = () => {
        this.setState({
            isUpdateVisible: false
        })
    };

    handleUpdateCancel = () => {
        this.setState({
            isUpdateVisible: false
        })
    };
    onFinish =async (values) => {
        console.log('Finish:', values);
        const res=await updateCategories({id:values._id,...values})
        console.log(res);
        if (res.code) {
            message.success(res.msg);
            this.getAllList()
            this.setState({
                isUpdateVisible: false
            })
        } else {
            message.warning(res.msg);
        }
    };
    render() {
        const { data } = this.props
        // console.log('data',data);
        const { isModalVisible, isUpdateVisible ,updateData} = this.state
        // 配置表格的每一列
        const columns = [
            {
                title: '类型名字',// 列的标题
                dataIndex: 'name',// 设置渲染数据的键名
                // key: 'name',//如果报错，并无法解决，更换为table里的rowKey
                width: 450,
                render: (text, record, index) => {
                    // console.log(text, record, index);
                    return <a>{text}</a>
                },//可以对当前数据进行额外的渲染，a标签是对里面的文本进行主题色渲染，具体看文档，有三个参数
            },
            {
                title: '类别',
                width: 450,
                dataIndex: 'type'
            },
            {
                title: '操作',
                width: 300,
                render: (text, record) => (
                    <Space size="middle">{/* 调整标签的间距，有单独文档 */}
                        {record.type==='一级分类'?<Button type="primary" onClick={() => {
                            this.setState({
                                parentId: record._id
                            },
                                () => {
                                    this.getAllList()
                                })
                        }}>查看子分类</Button>:''}
                        <Button type="dashed" size='middle' danger onClick={() => this.showUpdateModal(record)} >
                            编辑
                        </Button>
                        <Button type="primary" size='middle' danger onClick={() => this.deleteCategory(record._id)} >
                            删除
                        </Button>

                    </Space>
                ),
            },
        ];

        return (
            <Card title='商品类型' extra={this.state.parentId ? <a onClick={this.back}>返回上一级</a> : <a onClick={this.showModal}>新增分类</a>} bordered={false}>
                <Table rowKey='_id' columns={columns} dataSource={data} />
                <Modal title="添加分类信息" cancelText='退出' okText='确定' visible={isModalVisible} onOk={this.handleOk} onCancel={this.handleCancel}>
                    <AddCAtegory ref={this.inputRef} data={data}></AddCAtegory>
                </Modal>
                <Modal footer={null} title="修改商品" visible={isUpdateVisible} onOk={this.handleUpdateOk} onCancel={this.handleUpdateCancel}>
                    <Form
                        name="basic"
                        labelCol={{
                            span: 8,
                        }}
                        wrapperCol={{
                            span: 16,
                        }}
                        initialValues={
                            updateData
                        }
                        onFinish={this.onFinish}
                        autoComplete="off"
                        
                    >
                        <Form.Item
                            label="商品编号"
                            name="_id"
                        >
                            <Input />
                        </Form.Item>

                        <Form.Item
                            label="商品名称"
                            name="name"
                            rules={[
                                {
                                    required: true,
                                },
                            ]}
                        >
                            <Input />
                        </Form.Item>

                        <Form.Item
                            wrapperCol={{
                                offset: 8,
                                span: 16,
                            }}
                        >
                            <Button type="primary" htmlType="submit">
                               确认修改
                            </Button>
                        </Form.Item>
                    </Form>
                </Modal>
            </Card>
        )
    }
}

const mapStateToProps = state => {
    // console.log('组件中获取仓库中所有的数据', state.categories.data);
    return {
        data: state.categories.data
    }
}

export default connect(mapStateToProps)(Categories)